"""Lead statistics endpoints."""

from __future__ import annotations

from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session

from ...deps import get_current_user, get_stats_service, get_db
from ....models.user import User
from ....services.stats_service import StatsService
from ....services.quality_scoring_service import QualityScoringService
from ....repositories.lead_repository import LeadRepository
from ....schemas.stats import (
    OverviewStats,
    LeadsStatsResponse,
    QualityDistributionResponse,
    PriorityFollowupsResponse,
    PriorityLead,
    RecalculateQualityResponse,
)

router = APIRouter(prefix="/stats", tags=["stats"])


@router.get("/overview", response_model=OverviewStats)
def get_overview(
    stats_service: StatsService = Depends(get_stats_service),
    current_user: User = Depends(get_current_user),
) -> OverviewStats:
    """总览数据（客户总数、转化率、本周新增等）."""
    data = stats_service.get_overview(current_user.id)
    return OverviewStats(**data)


@router.get("/source-chart", response_model=dict[str, int])
def get_source_chart(
    stats_service: StatsService = Depends(get_stats_service),
    current_user: User = Depends(get_current_user),
) -> dict[str, int]:
    """来源渠道分布（饼图数据）."""
    return stats_service.get_source_chart(current_user.id)


@router.get("/stage-funnel", response_model=dict[str, int])
def get_stage_funnel(
    stats_service: StatsService = Depends(get_stats_service),
    current_user: User = Depends(get_current_user),
) -> dict[str, int]:
    """阶段漏斗图数据."""
    return stats_service.get_stage_funnel(current_user.id)


@router.get("/leads", response_model=LeadsStatsResponse)
def leads_stats(
    stats_service: StatsService = Depends(get_stats_service),
    current_user: User = Depends(get_current_user),
) -> LeadsStatsResponse:
    """旧版统计接口（向后兼容）."""
    by_channel = stats_service.channel_breakdown(current_user.id)
    by_stage = stats_service.stage_breakdown(current_user.id)
    return LeadsStatsResponse(by_channel=by_channel, by_stage=by_stage)


@router.get("/quality-distribution", response_model=QualityDistributionResponse)
def get_quality_distribution(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> QualityDistributionResponse:
    """获取客户质量等级分布统计.

    Returns:
        质量等级分布: {"S": 5, "A": 20, "B": 35, "C": 30, "D": 10}
    """
    lead_repo = LeadRepository(db)
    distribution = lead_repo.get_quality_distribution(owner_id=current_user.id)
    return QualityDistributionResponse(**distribution)


@router.get("/priority-followups", response_model=PriorityFollowupsResponse)
def get_priority_followups(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    limit: int = 20,
) -> PriorityFollowupsResponse:
    """获取今日优先跟进客户列表（Dashboard用）.

    筛选条件：
    - 质量分数 >= 70分
    - 超过3天未更新
    - 未成交/流失
    - 按质量分数降序

    Args:
        limit: 返回数量（默认20）

    Returns:
        优先跟进客户列表
    """
    lead_repo = LeadRepository(db)
    leads = lead_repo.get_priority_followups(
        owner_id=current_user.id,
        days_since_update=3,
        min_quality_score=70,
        limit=limit
    )

    # 转换为响应格式
    leads_data = [
        PriorityLead(
            id=lead.id,
            name=lead.name,
            phone=lead.phone,
            demand_type=lead.demand_type,
            quality_score=lead.quality_score,
            quality_grade=lead.quality_grade,
            stage=lead.stage,
            updated_at=lead.updated_at.isoformat() if lead.updated_at else None,
        )
        for lead in leads
    ]

    return PriorityFollowupsResponse(total=len(leads_data), leads=leads_data)


@router.post("/recalculate-quality", response_model=RecalculateQualityResponse)
def recalculate_quality_scores(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    limit: int = 100,
) -> RecalculateQualityResponse:
    """重新计算客户质量评分（批量更新）.

    Args:
        limit: 限制更新数量（默认100）

    Returns:
        更新数量统计
    """
    quality_service = QualityScoringService(db)
    updated_count = quality_service.batch_update_quality_scores(limit=limit)

    return RecalculateQualityResponse(
        updated_count=updated_count,
        message=f"成功更新 {updated_count} 个客户的质量评分"
    )
